#include "tab_widget.h"
#include "ui_tab_widget.h"
#include "writer.h"
#include <QDebug>


TabWidget::TabWidget(const QString &buddyName, QWidget *parent) :
    QWidget(parent),
    buddyName(buddyName),
    ui(new Ui::tab_widget)
{
    ui->setupUi(this);
}

TabWidget::~TabWidget()
{
    delete ui;
}

QListWidget *TabWidget::historico()
{
    return ui->listHistoricoChat;
}


void TabWidget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void TabWidget::on_b_close_clicked()
{
    deleteLater();
}

void TabWidget::on_b_send_buddy_clicked()
{
    QString txt = ui->txt_chatBuddy->toPlainText();
    int row = historico()->currentRow();
    if(!txt.isEmpty() ){
        QXmppMessage msg;
        msg.setTo(ui->l_privateBuddyName->text().remove("Chat with "));
        msg.setBody(Writer::privateText(txt));
        emit privateMessage(msg.body(), buddyName);
        historico()->addItem(" I wrote: " + txt);
        historico()->setCurrentRow(++row);
    }
    ui->txt_chatBuddy->clear();
}



void TabWidget::onChatText(const QString &body,const QString &from)
{
    ui->listHistoricoChat->addItem(new QListWidgetItem(from + ": " + body));
}

void TabWidget::on_txt_chatBuddy_textChanged()
{
    if(ui->txt_chatBuddy->document()->toPlainText().endsWith('\n')){
        on_b_send_buddy_clicked();
    }
}
